package com.learncloud.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author lbx
 * @version 1.0.0
 * @description 字段自动填充处理
 * @date 2020/1/28 13:43
 **/
@Slf4j
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     **/
    private final static String CREATE_TIME = "createTime";

    /**
     * 更新时间
     **/
    private final static String UPDATE_TIME = "updateTime";


    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, CREATE_TIME, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.fillUpdateStrategy(metaObject, UPDATE_TIME, new Date());
    }


    public MetaObjectHandler fillUpdateStrategy(MetaObject metaObject, String fieldName, Object fieldVal) {
        if (metaObject.hasGetter(fieldName)) {
            setFieldValByName(fieldName, fieldVal, metaObject);
        }
        return this;
    }
}
